<template>
  <div class="app-container batch-box">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="6" :md="6" :lg="4">
        <!-- 搜索 -->
        <el-input  v-model="searchName" placeholder="请输入分类名称" clearable size="small"
          prefix-icon="el-icon-search" style="margin-bottom:10px" />
        <!-- 分类数据 -->
        <Tree ref="tree" :sortTree="sortTree" :isHeight="isHeight" :loading="treeLoading" :isOperation="isOperation"
          @nodeClick="nodeClick(arguments)" :searchName="searchName" />
      </el-col>
      <!-- 搜索数据 -->
      <el-col :span="20" :xs="24">
        <el-form :inline="true" label-width="68px" style="margin-bottom: 15px;" v-hasPermi="['inv:batch:query']">
          <el-form-item label="物料编码">
            <el-input v-model="searchForm.searchCode" clearable size="small" style="width: 240px" />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="searchForm.searchName" clearable size="small" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <el-button v-hasPermi="['inv:batch:query']" type="primary" icon="el-icon-search" @click="search">搜索
            </el-button>
            <el-button v-hasPermi="['inv:batch:query']" icon="el-icon-refresh" @click="serchReset()">重置
            </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8 operation-btn">
          <el-col :span="1.5">
            <el-button type="primary" v-hasPermi="['inv:batch:query']" plain icon="el-icon-menu" size="mini" @click="checkleAll">查询所有</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-select class="select-attribute" v-model="selectAttribute" placeholder="请选择属性" @change="attributeChange">
              <el-option label="启用批号" value="enableBatch"></el-option>
              <el-option label="发料有零头" value="enableChip"></el-option>
              <el-option label="允许负库存" value="enableDebt"></el-option>
            </el-select>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" v-if="exportStatus=='sort'" plain icon="el-icon-download" size="mini"
              @click="handleExport" v-hasPermi="['inv:batch:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-printer" size="mini" @click="handlePrint"
              v-hasPermi="['inv:batch:print']">打印</el-button>
          </el-col>
        </el-row>
        <!-- 打印数据 -->
        <PrintPage :printData="printData" ref="startPrint" :title="printName" />
        <!-- 物料数据 -->
        <el-table v-loading="loading" :data="basicfileList" border :height="maxHeight">
          <el-table-column type="index" width="60" align="center" label="序号">
          </el-table-column>
          <el-table-column label="物料编码" align="center" sortable prop="code">
            <template slot-scope="scope">
              <span style="cursor: pointer;" @click.stop="seeMaterial(scope.row)">{{scope.row.code}}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" align="center" prop="name" sortable>
            <template slot-scope="scope">
              <span style="cursor: pointer;" @click.stop="seeMaterial(scope.row)">{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="型号规格" align="center" prop="attribute" width="150" />
          <el-table-column label="规格描述" align="center" prop="property" width="150" />
          <el-table-column label="主计量" align="center" prop="unitName" width="75" />
          <el-table-column label="启用批号" align="center" key="enableBatch" width="150">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enableBatch" active-value="1" inactive-value="0" disabled></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="发料有零头" align="center" key="enableChip" width="150">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enableChip" active-value="1" inactive-value="0" disabled></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="允许负库存" align="center" key="enableDebt" width="150">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enableDebt" active-value="1" inactive-value="0" disabled></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding" width="100">
            <template slot-scope="scope">
              <div class="public-btn">
                <el-button size="mini" type="text" class="basic-see" @click.stop="seeMaterial(scope.row)"
                  v-hasPermi="['inv:batch:view']">查看
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分类查询分页信息 -->
        <pagination v-show="total>=19" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getMaterialList" />
      </el-col>
    </el-row>

    <!-- 新增/查看/修改物料弹框信息 -->
    <el-dialog title="物料信息" :visible.sync="open" width="600px" v-if="open">
      <el-form ref="materialForm"  :model="materialForm" label-width="80px" size="medium"
        :disabled="butChange=='3'" :validate-on-rule-change="false" :hide-required-asterisk="star">
        <el-row>
          <el-col :span="24">
            <el-form-item label="分类信息" prop="value">
              <el-cascader v-model="value" :options="sortTree" ref="classTree" :props="classProps"
                @change="handleChange" class="cas-input" :disabled="butChange=='2'"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码">
              <el-input v-model="materialForm.code" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="更新时间">
              <el-input v-model="materialForm.updateTime" class="updata-time"></el-input>
            </el-form-item>
          </el-col>
          <!-- 左部开始 -->
          <el-col :span="12">
            <el-col :span="24">
              <el-form-item label="物料名称" prop="name">
                <el-input v-model="materialForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="主计量" prop="Form">
                <el-select v-model="packingForm" placeholder="请选择">
                  <el-option v-for="(item,index) in packingDate" :key="index" :label="item.name" :value="item.code">
                    <span>{{ item.name }}</span>
                    <span>（{{ item.code }}）</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="型号规格" prop="attribute">
                <el-input v-model="materialForm.attribute"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="规格描述" prop="property">
                <el-input v-model="materialForm.property"></el-input>
              </el-form-item>
            </el-col>
          </el-col>
          <!-- 左部结束 -->
          <!-- 右部开始 -->
          <el-col :span="12">
            <div style="overflow: hidden;margin-right: 10px;">
              <div class="ma-right">
                <el-col :span="24">
                  <el-form-item label="启用批号" prop="enableBatch" style="text-align: right;">
                    <el-switch v-model="materialForm.enableBatch" active-value="1" inactive-value="0"></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="发料有零头" prop="enableChip" style="text-align: right;">
                    <el-switch v-model="materialForm.enableChip" active-value="1" inactive-value="0"></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="允许负库存" prop="enableDebt" style="text-align: right;">
                    <el-switch v-model="materialForm.enableDebt" active-value="1" inactive-value="0"></el-switch>
                  </el-form-item>
                </el-col>
              </div>
            </div>
          </el-col>
          <!-- 右部结束 -->
        </el-row>
      </el-form>
      <!-- 物料数量表单 -->
      <div class="from-mount">
        <el-form :model="materialForm" label-width="100px" size="medium" class="mount-form" disabled>
          <el-row>
            <el-col :span="12">
              <el-form-item label="当前库存数量" class="txt-right">
                <el-input v-model="materialForm.quantity" class="now-stock"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际可用数量" class="txt-right">
                <el-input v-model="materialForm.available" class="now-actual"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划锁定数量">
                <el-input v-model="materialForm.mp" class="txt-right"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售锁定数量">
                <el-input v-model="materialForm.om" class="txt-right"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购在途数量">
                <el-input v-model="materialForm.po" class="txt-right"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产在途数量" class="txt-right">
                <el-input v-model="materialForm.prs"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="委外在途数量" class="txt-right">
                <el-input v-model="materialForm.pu"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

    </el-dialog>

  </div>
</template>

<script>
  import {
    getToken
  } from "@/utils/auth";
  import {
    listSort,
  } from "../../api/sort"; //分类接口
  import {
    listMaterial,
    listPacking,
    exportMaterial,
  } from "../../api/batch"; //物料接口
  import {
    getTreeData,
    getEcho,
  } from "../../utils/items" //js方法
  import Tree from "../../components/Sort/tree"; //分类组件
  import PrintPage from "../../components/Batch/print"; //打印组件
  import print from "print-js"; //打印js
  import {
    supParent
  } from "../../utils/sort.js" //打印获取分类名称
  export default {
    name: "Batch", //现存量
    data() {
      return {
        // 遮罩层
        loading: true,
        //物料树遮罩层
        treeLoading: false,
        //分类搜索名称
        searchName: "",
        // 批量删除按钮状态
        multiple: true,
        //是否显示分类操作按钮
        isOperation: true,
        //树形数据
        sortTree: [],
        //树形选中是否高亮
        isHeight: true,
        //物料数据最大高度
        maxHeight: null,
        //搜索参数
        searchForm: {
          searchName: "", //搜索物料名称
          searchCode: "", //搜索物料编码
        },
        //属性选择
        selectAttribute: "",
        // 料品查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          sortId: "",
          invName: "",
          invCode: "",
          enableBatch: "",
          enableChip: "",
          enableDebt: ""
        },
        butChange:"",
        star:"",
        // 总条数
        total: 0,
        //小数位数
        decimal: "4",
        //导出状态
        exportStatus: "sort",
        // 料品数据
        basicfileList: [],
        // 新增/修改/编辑对话框状态
        open: false,
        //选择分类回显信息
        value: [],
        //表单禁用状态
        seeStatus: false,
        //分类选择配置
        classProps: {
          children: "children",
          label: "sortName",
          value: "sortCode",
          checkStrictly: true
        },
        packingDate: [],
        // 主计量
        packingForm: "",
        // 物料新增/修改信息表单
        materialForm: {},
        //打印分类名称
        printName: "",
        //打印数据
        printData: [],

      }

    },
    created() {
      //初始化分类数据
      this.getTreeList();
      this.selectAttribute = "enableBatch";
      this.queryParams.enableBatch = "1";
      //初始化物料数据
      this.getMaterialList();
      // 初始化主计量
      this.getPacking()
      //隐藏操作按钮
      this.isOperation = false;
    },
    methods: {
      //获取分类数据
      getTreeList() {
        this.treeLoading = true;
        listSort({
          feature: ""
        }).then(res => {
          this.sortTree = getTreeData(res.data); //当children为0时，赋值undefined
          this.treeLoading = false;
        });
      },

      // 获取分类物料数据
      getMaterialList() {
        this.loading = true;
        listMaterial(this.queryParams).then(res => {
          if (res.code == 200) {
            let arrBasic = JSON.parse(JSON.stringify(res.rows));
            this.basicfileList = arrBasic;
            this.total = res.total;
            if (this.basicfileList.length >= 19) { //条数总数大于显示出现滚动条
              this.maxHeight = (`${document.documentElement.clientHeight}` - 270);
            } else {
              this.maxHeight = ""
            }
            this.loading = false;
          }

        })
      },
      //选择属性
      attributeChange() {
        if (this.selectAttribute == "enableBatch") {
          this.serchReset();
          this.queryParams.enableBatch = "1";
          this.queryParams.enableChip = "";
          this.queryParams.enableDebt = "";
          this.getMaterialList();
        } else if (this.selectAttribute == "enableChip") {
           this.serchReset();
          this.queryParams.enableBatch = "";
          this.queryParams.enableChip = "1";
          this.queryParams.enableDebt = "";
          this.getMaterialList();
        } else if (this.selectAttribute == "enableDebt") {
           this.serchReset();
          this.queryParams.enableBatch = "";
          this.queryParams.enableChip = "";
          this.queryParams.enableDebt = "1";
          this.getMaterialList();
        }

      },
      //搜索物料
      search() {
        if (this.searchForm.searchName == "" && this.searchForm.searchCode == "") {
          this.msgError("物料编码或物料名称不能同时为空！");
        } else {
          this.queryParams.invName = this.searchForm.searchName; //赋值物料名称
          this.queryParams.invCode = this.searchForm.searchCode; //赋值物料编码
          this.queryParams.sortId = ""; //避免当分类树点击时页面缓存的sortId导致搜索失败
          this.getMaterialList();
        }
      },

      //获取主计量数据
      getPacking() {
        return new Promise((resolve, reject) => {
          this.loading = true;
          listPacking().then(res => {
            if (res.code == 200) {
              this.packingDate = res.rows;
              this.loading = false;
              resolve();
            }
          }).catch(err => {
            this.msgError("获取主计量失败！");
          })
        })

      },

      //物料分类点击获取
      nodeClick(node) {
        this.selectwarehouse = "";
        // 获取上级分类名称
        const name = [];
        const getParentName = supParent(node[1], name).reverse(); //获取上级分类名称
        this.packingForm = node[0].unitCode; //获取默认主计量
        if (this.packingForm !== "") {
          this.handlePacking(node[0].unitCode); //得到单位编码与名称字段
        }
        const parentName = getParentName.join(" / "); //拼接上级分类名称
        if (node[1].data.parentId == 0) {
          this.printName = node[1].data.sortName + "-"; //主类上级分类为自身
        } else {
          this.printName = parentName + " / " + node[1].data.sortName + "-" //子类上级分类最终结果
        }
        this.undataAddSee(node[0].sortId).then(() => {
          this.isHeight = true; //打开分类树高亮
          this.exportStatus = "sort";
          this.queryParams.sortId = node[0].sortId; //赋值sortId用于搜索
          this.getMaterialList(); //重新拉取数据
        })
      },

      //选择主计量
      handlePacking(value) {
        if (this.packingDate.length > 0) {
          let obj = {};
          obj = this.packingDate.find((item) => {
            return item.code === value;
          });
          this.materialForm.unitCode = obj.code; //主计量编码
          this.materialForm.unitName = obj.name; //主计量名称
        }
      },

      // 查询所有
      checkleAll() {
        //清空搜索信息，避免干扰
        this.searchForm.searchName = "";
        this.searchForm.searchCode = "";
        this.queryParams.sortId = "";
        this.queryParams.invName = "";
        this.queryParams.invCode = "";
        this.selectAttribute = "";
        this.queryParams.enableBatch = "";
        this.queryParams.enableChip = "";
        this.queryParams.enableDebt = "";
        this.printName = "";
        this.isHeight = false; //关闭分类树高亮
        this.decimal = "4";
        this.getMaterialList();
      },

      //分类现存量导出
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所选物料数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportMaterial(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },


      // 打印
      handlePrint() {
        let number = 1;
        this.printData = this.basicfileList;
        this.printData.forEach(obj => {
          obj.id = number++
        })
        setTimeout(() => {
          this.$print(this.$refs.startPrint.$refs.print);
        }, 0)
      },

      // 分类选择回显结果
      handleChange(value) {
        value = value.join(""); //转换成字符串，用于传值后台
        this.materialForm.code = value;
        this.materialForm.sortId = this.$refs['classTree'].getCheckedNodes()[0].data.sortId; //赋值sortId
      },

      //查看物料
      seeMaterial(row) {
        this.undataAddSee(row.sortId).then(() => {
          // 格式化4位小数
          let basicMount = JSON.parse(JSON.stringify(row))
          basicMount.mp = this.Decimal(basicMount.mp);
          basicMount.om = this.Decimal(basicMount.om);
          basicMount.po = this.Decimal(basicMount.po);
          basicMount.prs = this.Decimal(basicMount.prs);
          basicMount.pu = this.Decimal(basicMount.pu);
          basicMount.quantity = this.Decimal(basicMount.quantity);
          basicMount.available = this.Decimal(basicMount.available);
          this.materialForm = basicMount;
          this.open = true;
          this.packingForm = row.unitCode;
        })
      },

      // 新增/修改/查看公共获取分类回显
      undataAddSee(id) {
        return new Promise((resolve, reject) => {
          let parentArr = [], //用于储存父类分类信息
            childrenArr = []; ////用于储存子类分类信息
          getEcho(id, this.sortTree, parentArr, childrenArr).then((res) => {
            setTimeout(() => {
           let success = [];
            for (let i = 0; i < res.length; i++) {
               if (success.indexOf(res[i]) === -1) {
                 success.push(res[i])
               }
             }
           let getNode = JSON.parse(JSON.stringify(success)) //拷贝vuex信息，避免影响源数据
              getNode.forEach(v => {
                if (v.ancestors.indexOf(",") > -1) { //是否是子分类
                  v.ancestors = v.ancestors.split(",").length; //拼接数组长度，用于排序
                } else {
                  v.ancestors = 1;
                }
              })
              getNode.sort((a, b) => { //排序得到正常的分类顺序，用于得到sortCode
                return a.ancestors - b.ancestors
              })
              let getCode = [];
              getNode.forEach(code => {
                getCode.push(code.sortCode);
                this.materialForm.sortId = code.sortId;
              })

              this.value = getCode; //对话框分类回显
              this.decimal = getNode[0].quantityDigit;
            }, 0)
          });
          resolve()
        })

      },
      //搜索表单重置
      serchReset() {
        for (let key in this.searchForm) {
          this.searchForm[key] = ""
        }
      },
    },

    components: {
      Tree,
      PrintPage
    },

  };
</script>
<style lang="scss">
  .batch-box {
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
      color: #1890FF;
    }

    .ma-right {
      .el-form-item {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }

      label {
        width: auto;
        flex-grow: 1;
      }

      .el-form-item__content {
        margin-left: 0px !important;
        margin-right: 0 !important;
      }
    }

    .height-tree2 {
      height: calc(100vh - 165px);
    }

    .el-switch.is-disabled {
      opacity: 1;
    }

    .select-attribute {
      input {
        line-height: 28px;
        height: 28px;
        width: 150px;
      }
    }

    .txt-right {
      input {
        text-align: right;
      }
    }

    .el-dialog__body {
      max-height: calc(100vh - 200px);
      overflow-y: auto;
    }

    .mount-title {
      font-size: 15px;
      font-weight: 700;
      margin: 0;
      border-bottom: 1px solid #dfe6ec;
      padding-bottom: 15px;
      margin-bottom: 15px;
    }

    .el-input--medium .el-input__icon {
      line-height: 28px;
    }

    .operation-btn {
      .is-disabled {
        span {
          font-weight: 700;
        }
      }


    }

    .el-table--medium th,
    .el-table--medium td {
      overflow: inherit;
    }

    .el-table th>.cell {
      overflow: inherit;
      position: relative;
    }

    .caret-wrapper {
      position: absolute;
      right: 64px;
      top: -5px;
      display: none;
    }

    .el-button--info.is-plain.is-disabled {
      color: #adaeaf;
    }

    .cas-input input {
      color: #1890FF !important;
    }

    .keep-status {
      margin-top: 15px;
    }

    .updata-time {
      input {
        border: none;
      }
    }

    .el-cascader .el-input .el-input__inner {
      color: #1890ff;
    }

    .el-input--suffix input {
      color: #606266;
    }

    .el-cascader--medium {
      width: 100%;
    }

    .has-gutter th {
      text-align: center;
      overflow: inherit;
    }

    .el-dialog__body {
      padding-right: 20px;
      padding-bottom: 20px;

    }

    .now-stock {
      input {
        color: #1890FF !important;
      }
    }

    .now-actual input {
      color: #13CE66 !important;
    }

    .el-input.is-disabled .el-input__inner {
      color: #333;
    }

    .el-form-item--medium .el-form-item__content {
      margin-right: 10px;
    }

    .cell {
      padding-right: 14px !important;
      padding-left: 14px !important;

      .basic-delete {
        color: #f56c6c;
      }


      .basic-see {
        color: #67c23a;
      }

      button:hover i {
        font-weight: 700;
      }

      button:hover span {
        font-weight: 700;
      }
    }

    .from-mount {
      padding: 15px;
      box-shadow: 1px 1px 10px 1px #eee;
      border-radius: 5px;
      padding-bottom: 10px;
      margin: 10px 10px 0px 10px;

      h3 {
        font-weight: normal;
        font-size: 15px;
        margin-top: 0;
        text-align: center;
        color: #1890ff;
      }
    }

    .foot-bot {
      text-align: inherit !important;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .foot-star {
        color: #1682e6;

        label {
          font-weight: normal;
          font-size: 12px;
        }
      }

    }
  }
</style>
